#include "PlayState.h"


PlayState::PlayState(GameContext& gc)
	:GameState(gc)
{
}


PlayState::~PlayState()
{
}

void PlayState::CheckCollision()
{
	
	//if enemy is active
	// is collected = false
	if(!diamond.isCollected())
	{
		SCircle eCircle = gCharacter.GetBoundingCircle();
		SCircle bCircle = diamond.GetBoundingCircle();

		float xDiff = eCircle.center.x - bCircle.center.x;
		float yDiff = eCircle.center.y - bCircle.center.y;
		
		//pythagorean to find connecting vector between bullet and enemy
		float distance = sqrt(xDiff * xDiff + yDiff * yDiff); 

		float radii = eCircle.radius + bCircle.radius;

		//if distance between e and b is less than combined radii, they have collided
		if(distance <= radii)
		{
			diamond.Kill();
			CollectedSound.Play();
		}

	}
	
}

void PlayState::Load() 
{
	const char* diamondNames[] =
	{
		"Diamond2.png",
		"Diamond.png",
		"Diamond3.png"
	};

	gCharacter.Load();
	CollectedSound.Load("collected.wav");
	gCharacter.SetPosition(SVector2(100.0f, 100.0f));
	diamond.Load(diamondNames[mGameContext.GetLevel() - 1]);
	const int kWinWidth = IniFile_GetInt("WinWidth", 800);
	const int kWinHeight = IniFile_GetInt("WinHeight", 600);
	SVector2 startPosition(kWinWidth * 0.20f, kWinHeight * 0.145f);
	diamond.SetPosition(startPosition);

	char levelName[256];
	char texturePackName[256];
	sprintf_s(levelName, 256, "level0%d.txt", mGameContext.GetLevel() );
	sprintf_s(texturePackName, 256, "texturepack0%d.txt", mGameContext.GetLevel() );
	gMap.Load(levelName, texturePackName);

	gFont.Load(24);
}

void PlayState::Unload() 
{
	gCharacter.Unload();
	CollectedSound.Unload();
	diamond.Unload();
	gMap.Unload();
	gFont.Unload();
}

NextState PlayState::Update(float deltaTime)
{
	gCharacter.Update(deltaTime, gMap);
	gMap.Update(deltaTime);
	diamond.Update(deltaTime,gMap);
	CheckCollision();
	// Are we done?

	NextState nextState = None;
	if (Input_IsKeyPressed(Keys::ESCAPE))
	{
		nextState = Frontend;
	}
	if (diamond.isCollected())
	{
		int currentLevel = mGameContext.GetLevel();
		if (currentLevel == 3)
		{
			nextState = Frontend;
		}
		else
		{
			mGameContext.SetLevel(currentLevel + 1);
			nextState = Gameplay;
		}
	}
	return nextState;

}

void PlayState::Render() 
{
	const SVector2 kTarget = gCharacter.GetPosition();
	const int kScreenWidth = IniFile_GetInt("WinWidth", 800);
	const int kScreenHeight = IniFile_GetInt("WinHeight", 600);
	const int kMapWidth = gMap.GetWidth();
	const int kMapHeight = gMap.GetHeight();

	SVector2 offset;
	offset.x = (kScreenWidth * 0.5f) - kTarget.x;
	offset.x = Clamp(offset.x, (float)kScreenWidth - kMapWidth, 0.0f);
	offset.y = (kScreenHeight * 0.5f) - kTarget.y;
	offset.y = Clamp(offset.y, (float)kScreenHeight - kMapHeight, 0.0f);

	gMap.Render(offset);
	gCharacter.Render(offset);
	diamond.Render(offset);	
	gFont.Print(gCharacter.GetCurrentState(), 0, 30);

}

